﻿using System;
using System.Globalization;
using System.Windows.Data;
using Iot.Shared.Helper;

namespace Iot.RealTimeData.WPF.Prism.ValueConverter;

/// <summary>
///     值到DateTime转换器，用于将时间戳转换为可读的日期时间格式
/// </summary>
public class ValueToDateTimeConverter : IValueConverter
{
    /// <summary>
    ///     纳秒到毫秒的转换常量，用于判断时间戳类型
    /// </summary>
    private const long Milliseconds = 1000000000000;

    /// <summary>
    ///     纳秒到秒的转换常量，用于判断时间戳类型
    /// </summary>
    private const long Seconds = 1000000000;

    /// <summary>
    ///     将时间戳值转换为DateTime格式
    /// </summary>
    /// <param name="value">要转换的时间戳值</param>
    /// <param name="targetType">目标类型</param>
    /// <param name="parameter">转换参数</param>
    /// <param name="culture">区域性信息</param>
    /// <returns>转换后的DateTime字符串表示，或特定标记值</returns>
    public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        // 使用switch表达式处理不同类型的时间戳
        return value switch
        {
            // 处理大于毫秒级时间戳的长整型
            long seconds and > Milliseconds => seconds.UnixTimeMilliseconds(),
            // 处理大于秒级时间戳的长整型
            long seconds and > Seconds => seconds.UnixTimeSeconds(),
            // 处理大于毫秒级时间戳的双精度浮点型
            double seconds and > Milliseconds => ((long)seconds).UnixTimeMilliseconds(),
            // 处理大于秒级时间戳的双精度浮点型
            double seconds and > Seconds => ((long)seconds).UnixTimeSeconds(),
            // 处理空值情况
            null => "==",
            // 处理其他情况
            _ => "--"
        };
    }

    /// <summary>
    ///     将DateTime值转换回时间戳
    /// </summary>
    /// <exception cref="NotImplementedException">该方法未实现</exception>
    public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}